<template>
  <div class="icon-selector">
    <div class="icon-preview" @click="showIconSelector = true">
      <font-awesome-icon v-if="modelValue" :icon="getIconObject(modelValue)" />
      <font-awesome-icon v-else :icon="['far', 'circle']" />
      <el-icon v-if="modelValue" class="clear-icon" @click.stop="emit('update:modelValue', '')">
        <!-- <ele-Close /> -->
        <el-icon><Close /></el-icon>
      </el-icon>
    </div>
    <el-input :value="modelValue" placeholder="请选择图标" disabled clearable @clear="emit('update:modelValue', '')" />
    <el-dialog v-model="showIconSelector" title="选择图标" :width="dialogWidth || '800px'" append-to-body>
      <div class="icon-search">
        <el-input v-model="iconSearch" placeholder="搜索图标" clearable />
      </div>
      <el-tabs v-model="activeTab" class="icon-tabs">
        <el-tab-pane label="实心图标" name="solid">
          <div class="icon-list">
            <div v-for="icon in filteredSolidIcons" :key="icon" class="icon-item" @click="selectIcon(icon)">
              <font-awesome-icon :icon="fas[icon]" />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="线框图标" name="regular">
          <div class="icon-list">
            <div v-for="icon in filteredRegularIcons" :key="icon" class="icon-item" @click="selectIcon(icon)">
              <font-awesome-icon :icon="far[icon]" />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="品牌图标" name="brands">
          <div class="icon-list">
            <div v-for="icon in filteredBrandIcons" :key="icon" class="icon-item" @click="selectIcon(icon)">
              <font-awesome-icon :icon="fab[icon]" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { fas } from "@fortawesome/free-solid-svg-icons";
import { far } from "@fortawesome/free-regular-svg-icons";
import { fab } from "@fortawesome/free-brands-svg-icons";

const props = defineProps<{
  modelValue: string;
  dialogWidth?: string;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();

const showIconSelector = ref(false);
const iconSearch = ref("");
const activeTab = ref("solid");

// 获取图标对象
const getIconObject = (iconString: string) => {
  if (!iconString) return ["fas", "question"];
  const [prefix, iconName] = iconString.split(" ");

  // 检查 iconName 是否存在
  if (!iconName) return ["fas", "question"];

  const cleanIconName = iconName.replace("fa-", "");

  if (prefix === "fas") {
    return fas[cleanIconName] || ["fas", "question"];
  } else if (prefix === "far") {
    return far[cleanIconName] || ["far", "question"];
  } else {
    return fab[cleanIconName] || ["fab", "question"];
  }
};

// 选择图标
const selectIcon = (icon: string) => {
  const prefix = activeTab.value === "solid" ? "fas" : activeTab.value === "regular" ? "far" : "fab";
  emit("update:modelValue", `${prefix} fa-${icon}`);
  showIconSelector.value = false;
};

// 获取所有图标名称
const getUniqueIcons = (iconSet: any) => {
  const uniqueIcons = new Set<string>();
  const iconNames = new Set<string>();

  Object.keys(iconSet).forEach(key => {
    if (key === "prefix" || key === "iconName") return;

    const icon = iconSet[key];
    if (icon && typeof icon === "object" && icon.iconName) {
      // 使用 iconName 作为唯一标识
      if (!iconNames.has(icon.iconName)) {
        iconNames.add(icon.iconName);
        uniqueIcons.add(key);
      }
    }
  });

  return Array.from(uniqueIcons);
};

const solidIcons = getUniqueIcons(fas);
const regularIcons = getUniqueIcons(far);
const brandIcons = getUniqueIcons(fab);

// 过滤图标
const filteredSolidIcons = computed(() => {
  if (!iconSearch.value) return solidIcons;
  const searchTerm = iconSearch.value.toLowerCase();
  return solidIcons.filter(icon => {
    const iconObj = fas[icon];
    return iconObj && typeof iconObj === "object" && iconObj.iconName.toLowerCase().includes(searchTerm);
  });
});

const filteredRegularIcons = computed(() => {
  if (!iconSearch.value) return regularIcons;
  const searchTerm = iconSearch.value.toLowerCase();
  return regularIcons.filter(icon => {
    const iconObj = far[icon];
    return iconObj && typeof iconObj === "object" && iconObj.iconName.toLowerCase().includes(searchTerm);
  });
});

const filteredBrandIcons = computed(() => {
  if (!iconSearch.value) return brandIcons;
  const searchTerm = iconSearch.value.toLowerCase();
  return brandIcons.filter(icon => {
    const iconObj = fab[icon];
    return iconObj && typeof iconObj === "object" && iconObj.iconName.toLowerCase().includes(searchTerm);
  });
});
</script>

<style scoped lang="scss">
.icon-selector {
  display: flex;
  gap: 12px;
  align-items: center;
  width: 100%;
  .icon-preview {
    position: relative;
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 32px;
    cursor: pointer;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
    &:hover {
      background-color: #ecf5ff;
      border-color: #409eff;
    }
    svg {
      font-size: 16px;
      color: #606266;
    }
    span {
      font-size: 12px;
      color: #909399;
    }
    .clear-icon {
      position: absolute;
      top: -8px;
      right: -8px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 16px;
      height: 16px;
      font-size: 12px;
      color: #ffffff;
      cursor: pointer;
      background-color: #f56c6c;
      border-radius: 50%;
      opacity: 0;
      transition: opacity 0.3s;
      &:hover {
        opacity: 1;
      }
    }
    &:hover .clear-icon {
      opacity: 1;
    }
  }
  :deep(.el-input) {
    flex: 1;
    width: auto;
  }
}
.icon-search {
  margin-bottom: 16px;
}
.icon-tabs {
  :deep(.el-tabs__content) {
    padding: 16px 0;
  }
}
.icon-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  gap: 12px;
  height: 400px;
  min-height: 400px;
  padding: 16px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  .icon-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    margin: 0 auto;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
    &:hover {
      background-color: #f5f7fa;
      border-color: #409eff;
    }
    svg {
      font-size: 20px;
      color: #606266;
    }
  }
}
</style>
